﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace FlashPay.Admin.Controllers
{
    using FlashPay.Admin.Mappers;
    using FlashPay.Admin.ViewModels.Company;
    using FlashPay.Service.Company;
    using FlashPay.Entity.Request.Company;
    using FlashPay.Entity.Response.Company;
    using Microsoft.AspNetCore.Mvc;
    using FlashPay.Entity;
    using FlashPay.Entity.Request.ExtApi;
    using FlashPay.Admin.ViewModels.Permission;
    using FlashPay.Entity.Response.User;
    using static FlashPay.Entity.PermissionHelper;
    using Microsoft.AspNetCore.Http;

    /// <summary>
    /// 公司管理
    /// </summary>
    public class CompanyController : BaseController
    {
        private readonly CompanyService companyService;

        public CompanyController(IAuthenticate<TicketResponse> _manage, IHttpContextAccessor _accessor, CompanyService companyService) : base(_manage, _accessor)
        {
            this.companyService = companyService;
        }

        #region 公司相关
        /// <summary>
        /// 公司新增
        /// </summary>
        [AuthorizeFilter(AuthCode.Company0002)]
        public JsonResult Add([FromBody] CompanyViewModel<String> model)
        {
            /* 資料驗證 */
            if (!this.TryValidateModel(model))
            {
            	return Json(Mapper.MapperResponse(model));
            }

            /* 補上必要資料 */
            model.CompanyPID = _manage.data.CompanyID;
            model.CreateUID = _manage.data.UserID;
            
            /* 轉換Model */
            CompanyRequest<String> request = Mapper.MapperRequest<String, String>(model);

            /* 呼叫Service層 */
            this.companyService.AddCompany(request);

            /* 結果複製 */
            model.Code = request.Code;
            model.Result = request.Result;
            model.Message = request.Message;
            model.Success = request.Success;

            /* 資料轉換並回傳JSON */
            return Json(Mapper.MapperResponse(model));
        }

        /// <summary>
        /// 公司修改
        /// </summary>
        [AuthorizeFilter(AuthCode.Company0003)]
        public JsonResult Edit([FromBody] CompanyViewModel<String> model)
        {
            /* 資料驗證 */
            if (model.CompanyID > 0)
            {
                /* 補上必要資料 */
                model.CompanyPID = _manage.data.CompanyID;
                model.UpdateUID = _manage.data.UserID;

                /* 轉換Model */
                CompanyRequest<String> request = Mapper.MapperRequest<String, String>(model);

                /* 呼叫Service層 */
                this.companyService.EditCompany(request);

                /* 結果複製 */
                model.Code = request.Code;
                model.Result = request.Result;
                model.Message = request.Message;
                model.Success = request.Success;
            }

            /* 資料轉換並回傳JSON */
            return Json(Mapper.MapperResponse(model));
        }

        /// <summary>
        /// 公司狀態變更
        /// </summary>
        [AuthorizeFilter(AuthCode.Company0004)]
        public JsonResult ChangeStatus(CompanyViewModel<String> model)
        {
            /* 資料驗證 */
            /* 考慮將此處延至Service層檢查 */
            if (model.CompanyID > 0 && model.CompanyStatus > 0 && model.CompanyStatus < 3)
            {
                /* 補上必要資料 */
                model.CompanyPID = _manage.data.CompanyID;
                model.UpdateUID = _manage.data.UserID;

                /* 轉換Model */
                CompanyRequest<String> request = Mapper.MapperRequest<String, String>(model);

                /* 呼叫Service層 */
                this.companyService.ChangeCompanyStatus(request);

                /* 結果複製 */
                model.Code = request.Code;
                model.Result = request.Result;
                model.Message = request.Message;
                model.Success = request.Success;
            }

            /* 資料轉換並回傳JSON */
            return Json(Mapper.MapperResponse(model));
        }

        /// <summary>
        /// 公司刪除
        /// </summary>
        [AuthorizeFilter(AuthCode.Company0006)]
        public JsonResult Delete(CompanyViewModel<String> model)
        {
            /* 資料驗證 */
            /* 考慮將此處延至Service層檢查 */
            if (model.CompanyID > 0)
            {
                /* 補上必要資料 */
                model.CompanyPID = _manage.data.CompanyID;
                model.UpdateUID = _manage.data.UserID;

                /* 轉換Model */
                CompanyRequest<String> request = Mapper.MapperRequest<String, String>(model);

                /* 呼叫Service層 */
                this.companyService.DeleteCompany(request);

                /* 結果複製 */
                model.Code = request.Code;
                model.Result = request.Result;
                model.Message = request.Message;
                model.Success = request.Success;
            }

            /* 資料轉換並回傳JSON */
            return Json(Mapper.MapperResponse(model));
        }

        /// <summary>
        /// 公司列表
        /// </summary>
        [AuthorizeFilter(AuthCode.Company0001)]
        public JsonResult Get([FromBody] CompanyViewModel<List<Object>> model)
        {
            if (model != null)
            {
                return GetCommon(model);
            }
            else
            {
                return Json(new JResult { Success = false, ErrorMessage = "未获取到数据" });
            }
        }

        //公共Get方法
        public JsonResult GetCommon([FromBody] CompanyViewModel<List<Object>> model)
        {
            var token = HttpContext.Request.Headers["token"];

            var ticketResponse = new TicketResponse();

            if (!string.IsNullOrEmpty(token))
            {
                ticketResponse = _manage.Get(token);
            }

            /* 補上必要資料 */
            model.CompanyPID = ticketResponse.CompanyID;

            #region 权限判断
            List<string> userPermission = ticketResponse.UserPermission;
            if (userPermission != null && userPermission.Count > 0)
            {
                userPermission = userPermission.Where(e => e.Contains("GetExtApi00")).ToList();
            }
            PermissionCompanyViewModel permissionModel = new PermissionCompanyViewModel();
            for (int i = 0; userPermission != null && i < userPermission.Count; i++)
            {
                //是否有——公司推送接口列表查看(存款)权限
                if (userPermission[i].Equals(AuthCode.GetExtApi001.ToString()))
                {
                    permissionModel.CanDepositView = true;
                }
                //是否有——公司推送接口列表查看(付款)权限
                if (userPermission[i].Equals(AuthCode.GetExtApi002.ToString()))
                {
                    permissionModel.CanPaymentView = true;
                }
                //是否有——公司推送接口列表查看(中转)权限
                if (userPermission[i].Equals(AuthCode.GetExtApi005.ToString()))
                {
                    permissionModel.CanTransferView = true;
                }
            }
            #endregion

            /* 轉換Model */
            CompanyRequest<List<CompanyResponse>> request = Mapper.MapperRequest<List<Object>, List<CompanyResponse>>(model);

            /* 呼叫Service層 */
            this.companyService.GetCompany(request);

            /* 結果複製 */
            model.Message = request.Message;

            model.Success = request.Success;
            model.TotalCount = request.TotalCount;

            model.Code = model.CompanyPID.ToString();//当前登陆人的CompanyID
            if (model.Success)
            {
                for (int i = 0; i < request.Result.Count; i++)
                {
                    request.Result[i].UpdateUID = Convert.ToInt32(model.Code);
                }
            }
            model.Result = new List<Object>(request.Result);

            //权限信息
            model.Permission = permissionModel;

            /* 資料轉換並回傳JSON */
            return Json(Mapper.MapperResponse(model));
        }


        //查看详情
        [AuthorizeFilter(AuthCode.Company0003, AuthCode.AllowEdit)]
        public JsonResult GetDetail([FromBody] CompanyViewModel<List<Object>> model)
        {
            if (model != null)
            {
                return GetCommon(model);
            }
            else
            {
                return Json(new JResult { Success = false, ErrorMessage = "未获取到数据" });
            }
        }

        /// <summary>
        /// 公司名稱檢查
        /// </summary>
        public JsonResult CheckName([FromBody] CompanyViewModel<Boolean> model)
        {
            /* 資料驗證 */
            /* 考慮將此處延至Service層檢查 */
            if (!String.IsNullOrWhiteSpace(model.CompanyName) || !String.IsNullOrWhiteSpace(model.CompanyNameEN))
            {
                /* 轉換Model */
                CompanyRequest<Boolean> request = Mapper.MapperRequest<Boolean, Boolean>(model);

                /* 呼叫Service層 */
                this.companyService.CheckCompanyName(request);

                /* 結果複製 */
                model.Code = request.Code;
                model.Result = request.Result;
                model.Message = request.Message;
                model.Success = request.Success;
            }

            /* 資料轉換並回傳JSON */
            return Json(Mapper.MapperResponse(model));
        }

        /// <summary>
        /// 驗證模型
        /// </summary>
        protected virtual Boolean TryValidateModel(Object model)
        {
            return base.TryValidateModel(model);
        }
        #endregion

        #region 公司接口授权
        /// <summary>
        /// 获取公司接口授权列表
        /// </summary>
        /// <param name="companyId">公司编号</param>
        public JsonResult GeteExtApi(int companyId)
        {
            var response = companyService.GeteExtApi(companyId);

            #region 权限判断
            List<string> userPermission = _manage.data.UserPermission;
            if (userPermission != null && userPermission.Count > 0)
            {
                userPermission = userPermission.Where(e => e.Contains("GetExtApi00")).ToList();
                //response.PermissionData = userPermission;

                PermissionExtApiViewModel permissionModel = new PermissionExtApiViewModel();
                for (int i = 0; userPermission != null && i < userPermission.Count; i++)
                {
                    //是否有——公司推送接口_中转_查看权限
                    if (userPermission[i].Equals(AuthCode.GetExtApi005.ToString()))
                    {
                        permissionModel.CanTransfer = true;
                    }
                    //是否有——公司推送接口_付款_查看权限
                    if (userPermission[i].Equals(AuthCode.GetExtApi002.ToString()))
                    {
                        permissionModel.CanPayment = true;
                    }
                    //是否有——公司推送接口_存款_查看
                    if (userPermission[i].Equals(AuthCode.GetExtApi001.ToString()))
                    {
                        permissionModel.CanDeposit = true;
                    }

                    //是否有——生成(中转)相关key权限
                    if (userPermission[i].Equals(AuthCode.GetExtApi006.ToString()))
                    {
                        permissionModel.CanTransferAdd = true;
                    }
                    //是否有——生成(付款)相关key权限
                    if (userPermission[i].Equals(AuthCode.GetExtApi004.ToString()))
                    {
                        permissionModel.CanPaymentAdd = true;
                    }
                    //是否有——生成(中转)相关key权限
                    if (userPermission[i].Equals(AuthCode.GetExtApi003.ToString()))
                    {
                        permissionModel.CanDepositAdd = true;
                    }
                }
                response.PermissionData = permissionModel;
            }
            #endregion

            return Json(response);
        }

        /// <summary>
        /// 获取推荐地址(详细)
        /// </summary>
        /// <param name="id">系统编号</param>
        public JsonResult GetExtApiPushUrl(int id)
        {
            var response = companyService.GetExtApiPushUrl(id);

            return Json(response);
        }

        /// <summary>
        /// 授权编辑(暂时舍弃)
        /// </summary>
        /// <param name="request">参数</param>
        public JsonResult ExtApiCompatEdit(List<ExtApiCompatEditRequest> request)
        {
           var response = companyService.ExtApiCompatEdit(request);
           return Json(response);
        }

        /// <summary>
        /// 授权编辑(新)
        /// </summary>
        /// <param name="request">参数</param>
        public JsonResult ExtApiCompatEditNew(string arrStr)
        {
            var result = new JResult()
            {
                Success = false
            };
            if (string.IsNullOrEmpty(arrStr))
            {
                result.ErrorMessage = "参数错误";
                return Json(result);
            }

            try
            {
                List<ExtApiCompatEditRequest> request = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ExtApiCompatEditRequest>>(arrStr);
                var response = companyService.ExtApiCompatEdit(request);
                return Json(response);
            }
            catch (Exception)
            {
                result.ErrorMessage = "发生异常";
                return Json(result);
            }
        }
        #endregion

        #region 推送地址
        /// <summary>
        /// 推送地址新增或编辑
        /// </summary>
        /// <param name="request"></param>
        public JsonResult ExtApiPushUrlAddOrEdit(ExtApiPushUrlAddOrEditRequest request)
        {
            var response = companyService.ExtApiPushUrlAddOrEdit(request);

            return Json(response);
        }

        /// <summary>
        /// 推送地址删除
        /// </summary>
        /// <param name="request"></param>
        public JsonResult ExtApiPushUrlDel(ExtApiPushUrlAddOrEditRequest request)
        {
            var response = companyService.ExtApiPushUrlDel(request);
            return Json(response);
        }
        #endregion
    }
}